<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片内容区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="getUser.query" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border style="width: 100%">
        <!-- 只需要给type的为index则可以表示出索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 所定义的值 -->
          <template slot-scope="scope">
            <!-- {{scope.row.mg_state}} -->
            <!-- scope.row所定义的值.row固定的语法 可以获取到里面的所有的数据 -->
            <el-switch v-model="scope.row.mg_state" @change="userChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip content="修改" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 分配按钮 -->
            <el-tooltip content="分配" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-share" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getUser.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="getUser.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <span>
        <el-form
          :model="addForm"
          status-icon
          :rules="addFormRules"
          ref="addFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <!-- disabled锁定,无法更改 -->
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <!-- prop是需要校验规则的项 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的兑换框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- rules是表单验证规则对象 -->
      <span>
        <el-form
          :model="editForm"
          status-icon
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名">
            <!-- disabled锁定,无法更改 -->
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <!-- prop是需要校验规则的项 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        //上面的值为布尔值
        //合法的邮箱
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/;
      if (regMobile.test(value)) {
        //上面的值为布尔值
        //合法的邮箱
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      getUser: {
        //用户输入的内容 双向数据绑定
        query: "",
        //当前的页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 2
      },
      //所获得的用户列表的数据
      userList: [],
      //所有的数据
      total: 0,
      //添加项的对话框
      addDialogVisible: false,
      //添加用户的表单信息
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //添加表单的验证规则对象
      addFormRules: {
        username: [
          {
            required: true,
            message: "请输名字",
            trigger: "blur"
          },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          {
            required: true,
            message: "请输密码",
            trigger: "blur"
          },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          {
            required: true,
            message: "请输邮箱",
            trigger: "blur"
          },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          {
            required: true,
            message: "请输手机号",
            trigger: "blur"
          },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //修改项的对话框
      editDialogVisible: false,
      //查询到的用户信息对象
      editForm: {},
      //修改表单验证规则对象
      editFormRules: {
        email: [
          {
            required: true,
            message: "请输邮箱",
            trigger: "blur"
          },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          {
            required: true,
            message: "请输手机号",
            trigger: "blur"
          },
          { validator: checkMobile, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.axios.get("users", {
        params: this.getUser
      });
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      if(res.data.users.length==0) {
        this.getUser.pagenum=this.getUser.pagenum-1
        this.getUserList()
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.getUser.pagesize = newSize;
      this.getUserList();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.getUser.pagenum = newPage;
      this.getUserList();
    },
    //监听开关状态的改变
    async userChange(userInfo) {
      console.log(userInfo);
      const { data: res } = await this.axios.put(
        "users/" + userInfo.id + "/state/" + userInfo.mg_state
      );
      console.log(res);
    },
    //展示编辑用户的对话框
    async showEditDialog(id) {
      this.editDialogVisible = true;
      console.log(id);
      const { data: res } = await this.axios.get("users/" + id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editForm = res.data;
    },
    //添加用户对话框的关闭事件
    addDialogClosed() {
      //resetFields()重置
      this.$refs.addFormRef.resetFields();
    },
    //点击确定添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.axios.post("users", this.addForm);
        if (res.meta.status !== 201)
          return this.$message.error("添加失败请重试");
        this.$message.success("添加成功");
        //然后再隐藏添加的对话框
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    //修改用户信息对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //点击确定修改用户信息
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid);
        if (!valid) return;
        const { data: res } = await this.axios.put(
          "users/" + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败请重试");
        }
        //然后再隐藏添加的对话框
        this.editDialogVisible = false;
        this.getUserList();
        this.$message.success("修改成功");
      });
    },
    //点击根据ID删除
    async removeUserById(ID) {
      //弹框提示是否删除
      const confirmRes = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err=>err)
      //点击确认返回的是字符串'confirm'
      //点击取消返回的是字符串'cancel'
      if(confirmRes !=="confirm") {
        return this.$message.info("已经取消删除")
      }
      this.axios.delete("users/"+ID).then(res=>{
        console.log(res);
        if(res.data.meta.status!==200){
          return this.$message.error("删除失败")
        }
        this.$message.success("删除成功") 
        this.getUserList();
      })
    }
  }
};
</script>
<style lang="less" scoped>
</style>
